/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.volatileengine.material.shader.xml;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.volatileengine.VolatileEngineException;
import com.volatileengine.material.shader.ShaderObject;
import com.volatileengine.material.shader.ShaderProgram;
import com.volatileengine.xml.IFileLoader;
import com.volatileengine.xml.XMLLoader;
import com.volatileengine.xml.XMLParsingException;
import com.volatileengine.xml.elements.Element;
import com.volatileengine.xml.elements.ResourceXMLElement;
import com.volatileengine.xml.elements.SimpleXMLElement;

/**
 * 
 * @author Administrator
 */
public class ShaderProgramXMLElement extends SimpleXMLElement<ShaderProgram> {

	private List<ShaderObject> objects;

	public ShaderProgramXMLElement() {
		this.objects = new ArrayList<ShaderObject>();
	}

	public String getAssociatedTag() {
		return "shaderprogram";
	}

	public Element<?> instantiateChild(String tagName, IFileLoader<?> loader) {
		if ("shaderobject".equalsIgnoreCase(tagName)) {
			return new ShaderObjectXMLElement();
		} else if ("resource".equalsIgnoreCase(tagName)) {
			return new ResourceXMLElement();
		}
		throw new XMLParsingException(getAssociatedTag() + " does not have " + tagName + " as a child");
	}

	public void endElement(IFileLoader<?> loader) {
		value = new ShaderProgram(objects);
	}

	public void processChild(Element<?> child, IFileLoader<?> loader) {
		if ("shaderobject".equalsIgnoreCase(child.getAssociatedTag())) {
			objects.add((ShaderObject) child.getValue());
		} else if ("resource".equalsIgnoreCase(child.getAssociatedTag())) {
			try {
				IFileLoader<ShaderObject> resourceLoader = new XMLLoader<ShaderObject>(new ShaderObjectXMLElement());
				resourceLoader.setResourceFinder(loader.getResourceFinder());

				objects.add(resourceLoader.load((String) child.getValue(), null));
			} catch (IOException ex) {
				throw new VolatileEngineException(ex);
			}

		}
	}
}
